from rest_framework.generics import ListAPIView,RetrieveAPIView
from rest_framework.views import APIView

from apps.recruit.models import Recruit
from apps.recruit.serializers.JobDetailSerializer import JobDetailModelSerializer
from apps.recruit.serializers.JobSerializer import JobObtainModelSerializer
from rest_framework.response import Response


# 推荐职位
class RecommendJobAPIView(ListAPIView):
    queryset = Recruit.objects.order_by('-visits')[:4] # 根据浏览数升序，取前4个
    serializer_class = JobObtainModelSerializer


# 最新职位
class LatestJobAPIView(ListAPIView):
    queryset = Recruit.objects.order_by('-createtime')[:4]  # 根据创建时间降序，取前4个
    serializer_class = JobObtainModelSerializer


# 职位详情
class DetailJobAPIView(RetrieveAPIView):
    queryset = Recruit.objects.all()
    serializer_class = JobDetailModelSerializer


# 职位访问量统计
class JobVisitView(APIView):
    def put(self,request,pk):
        job = Recruit.objects.get(id=pk)
        job.visits += 1
        job.save()

        return Response({"message":"更新成功","success":True})


# 职位收藏  ==> 登录状态下
class CollectJobView(APIView):
    def post(self,request,pk):
        user = request.user
        recruit = Recruit.objects.get(id=pk)
        users = recruit.users.all()
        if user not in users:
            recruit.users.add(user)
            return Response(data={"message": "收藏成功", "success": True})


# 职位取消收藏 ==> 登录状态下
class CancelCollectJobView(APIView):
    def post(self,request,pk):
        user = request.user
        recruit = Recruit.objects.get(id=pk)
        users = recruit.users.all()
        if user in users:
            recruit.users.remove(user)
            return Response(data={"message": "成功取消收藏", "success": True})


"""前端发送post请求，包含cityname和keyword两个参数,
cityname固定请求，keyword是在cityname读取的内容中再进行的筛选
先实现第一步，对cityname的筛选，后再根据keyword来筛选"""

# 职位搜索
class searchJobView(APIView):
    def post(self,request):
        cityname = request.data.get('cityname')
        keyword = request.data.get('keyword')
        if cityname:
            queryset = Recruit.objects.filter(city=cityname)

            if keyword.isspace() or keyword is None:
                queryset = queryset.all()
            else:
                queryset = queryset.filter(jobname__icontains=keyword.strip())

        else:
            queryset = Recruit.objects.filter(jobname__icontains=keyword)

        serializer = JobObtainModelSerializer(instance=queryset,many=True)

        return Response(serializer.data)




# 路由 - 视图
RecommendJob = RecommendJobAPIView.as_view()
LatestJob = LatestJobAPIView.as_view()
DetailJob = DetailJobAPIView.as_view()
JobVisit = JobVisitView.as_view()
JobCollect = CollectJobView.as_view()
JobCancelCollect = CancelCollectJobView.as_view()
JobSearch = searchJobView.as_view()